package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

import com.huike.report.domain.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;


    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;

    @Autowired
    private ReportMapper reportMpper;


    /**
     * 渠道统计
     */
    @Override
    public List<Map<String, Object>> chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.chanelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
            datum.put("channel", lable);
        }
        return data;
    }

    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
        return contractMapper.selectTbContractList(tbContract);
    }


    @Override
    public List<Map<String, Object>> activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.activityStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long activityId = (Long) datum.get("activity_id");
            TbActivity tbActivity = activityMapper.selectTbActivityById(activityId);
            if (tbActivity == null) {
                datum.put("activity", "其他");
            } else {
                datum.put("activity", tbActivity.getName());
            }
        }
        return data;
    }

    /**
     * 按照部门统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.deptStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return data;
    }


    /**
     * 按照渠道统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data = contractMapper.channelStatistics(beginCreateTime, endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue = (String) datum.get("channel");
            if (subjectValue != null) {
                String lable = sysDictDataMapper.selectDictLabel("clues_item", subjectValue);
                datum.put("channel", lable);
            }
        }
        return data;
    }


    /**
     * 按照归属人统计销售
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
        return contractMapper.ownerShipStatistics(beginCreateTime, endCreateTime);
    }


    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities = activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list = new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if (clueCount.get("falseClues") != null) {
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if (contractCount.get("amount") == null) {
                    dto.setAmount(0d);
                } else {
                    dto.setAmount((Double) contractCount.get("amount"));
                }
                if (contractCount.get("cost") == null) {
                    dto.setCost(0d);
                } else {
                    dto.setCost((Double) contractCount.get("cost"));
                }

            }
            list.add(dto);
        }
        return list;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId = request.getDeptId();
        TbAssignRecord tbAssignRecord = new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }


    /**
     * 获取首页基本数据
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1 构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        // 2.2 开始查询第一个属性 线索数量
        result.setCluesNum(reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
        // 2.3 开始查询第一个属性 商机数量
        result.setBusinessNum(reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
        // 2.4 开始查询第一个属性 合同数量
        result.setContractNum(reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setSalesAmount(reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));
        //5 返回结果集对象
        return result;
    }

    //重写
    @Override
    public IndexVodai getVo(String beginCreateTime, String endCreateTime) {
        IndexVodai result = new IndexVodai();
        String username = SecurityUtils.getUsername();
        // 2.2 待跟进线索
        result.setTofollowedCluesNum(reportMpper.getCluesNumdai(beginCreateTime, endCreateTime, username));
        // 2.3 待跟进商机
        result.setTofollowedBusinessNum(reportMpper.getBusinessNumdai(beginCreateTime, endCreateTime, username));
        // 2.4 待分配线索
        result.setToallocatedCluesNum(reportMpper.getContractNumfen(beginCreateTime, endCreateTime, username));
        // 2.5 待分配商机
        result.setToallocatedBusinessNum(reportMpper.getSalesAmountfen(beginCreateTime, endCreateTime, username));
        return result;
    }

    //统计创建线索及总数
    @Override
    public HashMap<String, List> getcluesStatistics(String beginCreateTime, String endCreateTime) {
        Date date = new Date();
        HashMap<String, List> map = new HashMap<>();
        Calendar c = Calendar.getInstance();
        Calendar d = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date begin = null;
        Date end = null;
        try {
            begin = simpleDateFormat.parse(beginCreateTime);
            end = simpleDateFormat.parse(endCreateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(begin);
        d.setTime(end);
        d.add(Calendar.DAY_OF_MONTH, 1);
        //日期数组
        ArrayList<Object> clue = new ArrayList<>();
        ArrayList<Object> series = new ArrayList<>();
        //新增线索数量数组
        ArrayList<Object> createsum = new ArrayList<>();
        //线索总数量数组
        ArrayList<Object> sum = new ArrayList<>();
        while (c.before(d)) {
            Date date1 = new Date();
            date1 = c.getTime();
            String format = simpleDateFormat.format(date1);
            //格式化时间进行搜索
            Integer clue1 = reportMpper.getClue(format);
            createsum.add(clue1);
            Integer clueSum = reportMpper.getClueSum(format);
            sum.add(clueSum);

            clue.add(format);
            c.add(Calendar.DAY_OF_MONTH, 1);
        }

        HashMap<Object, Object> map1 = new HashMap<>();
        HashMap<Object, Object> map2 = new HashMap<>();
        map1.put("name", "新增线索数量");
        map1.put("data", createsum);
        map2.put("name", "线索总数量");
        map2.put("data", sum);
        series.add(map1);
        series.add(map2);
        map.put("xAxis", clue);
        map.put("series", series);
        return map;

    }

    //统计学科占比
    @Override
    public List getsubjectStatistics(String beginCreateTime, String endCreateTime) {
        List data = new ArrayList<>();
        //获得学科
        List<Integer> list = reportMpper.getsubject();
        //获得学科总数
        for (Object l : list) {
            Integer l1 = (Integer) l;
            Integer sum = reportMpper.getsubSum(beginCreateTime, endCreateTime, l1);
            HashMap<String, Object> map = new HashMap<>();
            if (sum != 0) {
                map.put("num", sum);
                if (l1 == 0) {
                    map.put("subject", "java");
                } else if (l1 == 1) {
                    map.put("subject", "前端");
                } else if (l1 == 2) {
                    map.put("subject", "人工智能");
                } else if (l1 == 3) {
                    map.put("subject", "大数据");
                } else if (l1 == 4) {
                    map.put("subject", "Python");
                } else if (l1 == 6) {
                    map.put("subject", "测试");
                } else if (l1 == 7) {
                    map.put("subject", "新媒体");
                } else if (l1 == 8) {
                    map.put("subject", "产品");
                } else if (l1 == 9) {
                    map.put("subject", "UI");
                }
//           }else {
//               map.put("subject", l1);
//           }

                data.add(map);
            }
        }
        return data;
    }

    //线索转换效率
    @Override
    public Map<String, Integer> getVulnerabilityMap(String beginCreateTime, String endCreateTime) {
        Integer cluesNumsmap = reportMpper.getcluesNumsmap(beginCreateTime, endCreateTime);
        Integer cluesNumsmapYOU = reportMpper.getcluesNumsmapYOU(beginCreateTime, endCreateTime);
        Integer BusinessNummap = reportMpper.getBusinessNummap(beginCreateTime, endCreateTime);
        Integer ContractNummap = reportMpper.getContractNummap(beginCreateTime, endCreateTime);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("cluesNums",cluesNumsmap);
        map.put("effectiveCluesNums",cluesNumsmapYOU);
        map.put("businessNums",BusinessNummap);
        map.put("contractNums",ContractNummap);
        return map;

    }

    //商机转换
    @Override
    public List<Tagger> getcuntegger(String beginCreateTime, String endCreateTime){
        Integer businessNummap = reportMpper.getBusinessNummap(beginCreateTime,endCreateTime);
        List<Tagger> list = reportMpper.getzhuanhualv(beginCreateTime, endCreateTime);
        for (Tagger tagger : list) {
            Integer num = Integer.valueOf(tagger.getNum());
            BigDecimal bigDecimal = new BigDecimal((float)num / businessNummap).setScale(2, BigDecimal.ROUND_HALF_UP);
            String s = String.valueOf(bigDecimal);
            tagger.setRadio(s);
        }
        return list;
    }
    //线索转换
    @Override
    public List<Tagger> getcuntegger2(String beginCreateTime, String endCreateTime){
        Integer integer = reportMpper.getcluesNumsmapYOU(beginCreateTime,endCreateTime);
        List<Tagger> list = reportMpper.getzhuanhualv2(beginCreateTime, endCreateTime);
        for (Tagger tagger : list) {
            Integer num = Integer.valueOf(tagger.getNum());
            BigDecimal bigDecimal = new BigDecimal((float)num / integer).setScale(2, BigDecimal.ROUND_HALF_UP);
            String s = String.valueOf(bigDecimal);
            tagger.setRadio(s);
        }
        return list;

    }

}